package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class BootstrapNew {

    /** servlet存储器 */
    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    /** webapps存储器 */
    private Map<String, String> webappsMap = new HashMap<>();
    /** servlet连接器 */
    private Connector connector = new Connector();
    /** 引擎组件 */
    private Engine engine;
    /** host列表 */
    private List<Host> hosts = new ArrayList<>();


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
//        loadServlet();
        // 加载解析相关的配置，server.xml, 每个项目都有自己的web.xml，需要解析
        loadServer();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /*
            完成Minicat 4.0版本
            需求：模拟出webapps部署效果，磁盘上放置⼀个webapps目录，webapps中可以有多个项目，比如demo1,demo2,demo3...
         */
        for (Host host : hosts) {
            ServerSocket serverSocket = new ServerSocket(connector.getPort(), 0, InetAddress.getByName(host.getName()));
            System.out.println("=====>>>Minicat start on port：" + connector.getPort());
            System.out.println("=========>>>>>>使用线程池进行多线程改造");
            /*
                多线程改造（使用线程池）
             */
            Runnable runnable = () ->{
                while(true) {
                    try {
                        System.out.println("====开始");
                        Socket socket = serverSocket.accept();
                        socket.setSoTimeout(connector.getConnectionTimeout());
                        RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap, host.getAppBase());
                        //requestProcessor.start();
                        threadPoolExecutor.execute(requestProcessor);
                        System.out.println("====结束");
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            };

            runnable.run();

        }


    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(String path, String dirPath) {
        /*InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();*/

        try {
            InputStream resourceAsStream = new FileInputStream(new File(dirPath + "/web.xml"));
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            MyClassLoader myClassLoader = new MyClassLoader(dirPath);
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Class<?> aClass = myClassLoader.findClass(servletClass);
                System.out.println(aClass);
//                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
                servletMap.put(path + urlPattern, (HttpServlet) aClass.newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    private void loadServer(){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element serviceElement = rootElement.element("Service");
            Element connectorElement = serviceElement.element("Connector");

            connector.setConnectionTimeout(Integer.valueOf(connectorElement.attribute("connectionTimeout").getValue()));
            connector.setPort(Integer.valueOf(connectorElement.attribute("port").getValue()));

            Element engineElement = serviceElement.element("Engine");
            String engineName = engineElement.attribute("name").getValue();
            String defaultHost = engineElement.attribute("defaultHost").getValue();
            engine = new Engine(engineName, defaultHost);

            List<Element> hostElements = engineElement.elements("Host");
            for (Element hostElement : hostElements) {
                String name = hostElement.attribute("name").getValue();
                if(null == null || "".equals(name)){
                    name = engine.getDefaultHost();
                }
                String appBase = hostElement.attribute("appBase").getValue();
                Host host = new Host(name, appBase);
                hosts.add(host);
                List<Element> contextElements = hostElement.elements("Context");

                for (Element contextElement : contextElements) {
                    String docBase = contextElement.attribute("docBase").getValue();
                    String path = contextElement.attribute("path").getValue();
                    loadServlet(path, appBase + docBase);
                }

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        BootstrapNew bootstrap = new BootstrapNew();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
